package com.pai4j.zwiki.controller;

import com.pai4j.zwiki.domain.entity.ThesisVersionEntity;
import com.pai4j.zwiki.service.InteractiveThesisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交互式论文生成控制器
 * 支持模板上传、智能填充、预览、反馈、优化的完整交互流程
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/thesis/interactive")
@RequiredArgsConstructor
public class InteractiveThesisController {

    private final InteractiveThesisService interactiveThesisService;

    /**
     * 步骤1：上传论文模板（可选）
     */
    @PostMapping("/upload-template/{taskId}")
    public ResponseEntity<Map<String, Object>> uploadTemplate(
            @PathVariable String taskId,
            @RequestParam(value = "template", required = false) MultipartFile templateFile) {
        
        log.info("上传论文模板, 任务ID: {}", taskId);

        try {
            Map<String, Object> templateStructure = interactiveThesisService
                    .uploadAndAnalyzeTemplate(taskId, templateFile);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "模板上传成功");
            result.put("data", templateStructure);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("上传模板失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "上传失败: " + e.getMessage());

            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 步骤2：智能填充论文
     */
    @PostMapping("/fill/{taskId}")
    public ResponseEntity<Map<String, Object>> fillThesis(
            @PathVariable String taskId,
            @RequestParam String templatePath) {
        
        log.info("智能填充论文, 任务ID: {}", taskId);

        try {
            String versionId = interactiveThesisService.intelligentFillThesis(taskId, templatePath);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "论文填充完成");
            result.put("data", Map.of("versionId", versionId));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("填充论文失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "填充失败: " + e.getMessage());

            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 步骤3：预览论文（HTML格式）
     */
    @GetMapping("/preview/{taskId}")
    public ResponseEntity<Map<String, Object>> previewThesis(
            @PathVariable String taskId,
            @RequestParam(required = false) Integer version) {
        
        log.info("预览论文, 任务ID: {}, 版本: {}", taskId, version);

        try {
            String htmlPreview = interactiveThesisService.getThesisPreview(taskId, version);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "预览加载成功");
            result.put("data", Map.of("htmlContent", htmlPreview));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("预览论文失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "404");
            result.put("message", "论文不存在");

            return ResponseEntity.status(404).body(result);
        }
    }

    /**
     * 步骤4：提交反馈
     */
    @PostMapping("/feedback")
    public ResponseEntity<Map<String, Object>> submitFeedback(
            @RequestBody Map<String, Object> feedbackData) {
        
        String taskId = (String) feedbackData.get("taskId");
        Integer version = (Integer) feedbackData.get("version");
        String section = (String) feedbackData.get("section");
        String feedbackType = (String) feedbackData.get("feedbackType");
        String feedbackContent = (String) feedbackData.get("feedbackContent");

        log.info("提交反馈, 任务ID: {}, 章节: {}, 类型: {}", taskId, section, feedbackType);

        try {
            Long feedbackId = interactiveThesisService.submitFeedback(
                    taskId, version, section, feedbackType, feedbackContent);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "反馈已提交");
            result.put("data", Map.of("feedbackId", feedbackId));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("提交反馈失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "提交失败: " + e.getMessage());

            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 步骤5：根据反馈优化论文
     */
    @PostMapping("/optimize/{feedbackId}")
    public ResponseEntity<Map<String, Object>> optimizeThesis(
            @PathVariable Long feedbackId,
            @RequestParam String taskId) {
        
        log.info("根据反馈优化论文, 反馈ID: {}", feedbackId);

        try {
            String newVersionId = interactiveThesisService.optimizeThesisBasedOnFeedback(
                    taskId, feedbackId);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "论文已优化");
            result.put("data", Map.of("newVersionId", newVersionId));

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("优化论文失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "优化失败: " + e.getMessage());

            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 查看版本历史
     */
    @GetMapping("/versions/{taskId}")
    public ResponseEntity<Map<String, Object>> getVersionHistory(@PathVariable String taskId) {
        log.info("查看版本历史, 任务ID: {}", taskId);

        try {
            List<ThesisVersionEntity> versions = interactiveThesisService.getVersionHistory(taskId);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "查询成功");
            result.put("data", versions);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询版本历史失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "查询失败");

            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 确认最终版本
     */
    @PostMapping("/confirm/{taskId}")
    public ResponseEntity<Map<String, Object>> confirmFinalVersion(
            @PathVariable String taskId,
            @RequestParam Integer version) {
        
        log.info("确认最终版本, 任务ID: {}, 版本: {}", taskId, version);

        try {
            interactiveThesisService.confirmFinalVersion(taskId, version);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "0");
            result.put("message", "已确认为最终版本");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("确认版本失败", e);

            Map<String, Object> result = new HashMap<>();
            result.put("code", "500");
            result.put("message", "确认失败");

            return ResponseEntity.internalServerError().body(result);
        }
    }
}

